/*
 * @Author: WangLong
 * @Date: 2024-01-16 17:06:48
 * @LastEditTime: 2024-02-23 18:25:16
 * @LastEditors: MoWanPing
 * @Description:
 * @FilePath: \jnks_low_air_front_gov_online\src\utils\geoMap.js
 */
// import "@/utils/CesiumNetworkPlug.min.js";
import Data from "./wenzhou";
import * as turf from "@turf/turf";
import { ElMessage } from "element-plus";
import { set } from "nprogress";
let aMap = null;
let buildingLayer = null; //3D楼快
let layers = null;
let mouseTool = null;
let OpnePop = null;
let satelliteLayer = null;
let mapStatus = "SW";
var disProvince;
var colors = {};
let divisionName = "杭州市";
let borderList = [];
let roadNetLayer = null;
let maskObj = null;
let changeDefaultView = function () { };
let defaultViewShowFun = function () { };
let suoFangDefaultFun = function () { };
//热力图
let heatmap = null; //热力图数据
let heatmapData = Data;
//反制设备数据
let orientationInfoList = [];
let orientationCircleList = []; // 存放定向设备范围区域
let orientationSector = {}; // 存放定向设备扇形区域
let deviceOptions = [
  {
    deviceId: 631,
    id: 6981,
    name: "黄龙体育中心-定向反制",
    status: 1,
    typeId: 5,
    creTime: "2024-01-29 15:21:06",
    longitude: "120.101225",
    latitude: "30.262237",
    isUnmanned: 0,
    type: 2,
    strikeSeconds: 60,
    strikeRadius: null,
    trackCalibrationAngle: null,
    calibrationChangeAngle: null,
    trackDisable: null,
    colourCss: "#c1bd68",
    includedAngle: null,
    sectorRadius: null,
    installHeight: 80,
    unattendedState: false,
    countdown: false,
  },
];
let sectortimer = {}; //反制设备开启动画的定时器
let closeSectortimer = {}; //反制设备关闭动画的定时器
let deviceCount = {
  631: {
    timer: null,
    count: 60,
    countdown: true,
    counterType: "",
  },
}; //下发任务时count，timer
let sectorarr = []; //开启反制的数组

class Controller {
  labelMarker = null;
  aMap = null;
  companyLayer = null;
  mhAirportLayer = null;
  thAirportLayer = null;
  czAirportLayer = null;
  UAVAirportLayer = null;
  zhenceLayer = null;
  fanzhiLayer = null;
  wxdLayer = null;
  weatherDeviceLayer = null;
  youpianLayer = null;
  PopularPointslayer = null;
  removeMarkers = []; //清除坠机点的数组
  mapCenter = [];
  constructor(mapCenter, openPop) {
    this.aMap = null;
    this.mapCenter = mapCenter;
    OpnePop = openPop;
  }
  /**
   * @description:  初始化地图
   */
  initMap(mapID, changeDefault, suoFangDefault) {
    changeDefaultView = changeDefault;
    suoFangDefaultFun = suoFangDefault;
    aMap = new AMap.Map(mapID, {
      viewMode: "3D",
      zoom: 12.2, // 初始化地图级别
      zooms: [2, 18],
      // zooms: [15, 20],
      pitch: 45,
      rotation: 5, // 顺时针旋转
      center: this.mapCenter, //120.132648, 30.266278
      // mapStyle: "amap://styles/effd80d7df65e5fe9e937be74f6d0262",
      mapStyle: "amap://styles/4903b095599cca725b8f2c0951dcd6e4",
      // showLabel: true,
      // skyColor: "rgba(0,0,0,0)"
      zIndex: 1,
    });

    // aMap.on('click', function (e) {
    //   // if (e.domEvent) {
    //   //   e.domEvent.stopPropagation();
    //   // }
    //   // 处理地图点击事件的逻辑
    // });

    buildingLayer = new AMap.Buildings({
      heightFactor: 1,
      wallColor: "#00355F",
      roofColor: "#43E1FF",
      zIndex: 1, // zooms: [0, 20],
      zooms: [2, 18]
    });
    layers = [AMap.createDefaultLayer(), buildingLayer];
    aMap.add(layers);
    this.aMap = aMap;
    roadNetLayer = new AMap.TileLayer.RoadNet();
    // aMap.setLayers([roadNetLayer, Satellite])
    aMap.on("zoomchange", (e) => {
      var zoom = aMap.getZoom();
      changeDefaultView();
      if (mapStatus === "SW") {
        if (zoom >= 14.91) {
          roadNetLayer.show();
        } else {
          roadNetLayer.hide();
        }
      }
    });

    aMap.on("moveend", () => {
      changeDefaultView();
    });

    aMap.on("zoomend", () => {
      if (aMap.getCenter().toString() === "120.180924,30.186115") {
        suoFangDefaultFun();
      }
    });

    aMap.on("click", (e) => {
      console.log("获取点的坐标", e.lnglat.getLng() + "," + e.lnglat.getLat());
    });

    this.drawAdministrativeDivisions("杭州市");
    return aMap;
  }

  /**
   * @description: 切换卫星地图
   */
  swicthSatellite = () => {
    satelliteLayer = new AMap.TileLayer.Satellite();
    this.aMap.add(satelliteLayer);
    this.aMap.remove(layers);
    roadNetLayer.hide();
    maskObj.visible = false;
    mapStatus = "WX";
    roadNetLayer.hide();
  };

  showVectorMap() {
    this.aMap.add(layers);
    if (satelliteLayer) satelliteLayer.hide();
    roadNetLayer.show();
    if (maskObj) maskObj.visible = true;
    this.aMap.setMapStyle("amap://styles/4903b095599cca725b8f2c0951dcd6e4");
  }

  show3DMap() {
    if (satelliteLayer) satelliteLayer.hide();
    roadNetLayer.hide();
    this.aMap.remove(layers);
    if (maskObj) maskObj.visible = false;
    this.aMap.setMapStyle("amap://styles/normal");
  }

  /**
   * @description: 绘制行政区划
   */
  drawAdministrativeDivisions(name) {
    let _this = this;
    //加载行政区划插件
    // if (!_this.district) {
    //实例化DistrictSearch
    var opts = {
      subdistrict: 1, //获取边界不需要返回下级行政区
      extensions: "all", //返回行政区边界坐标组等具体信息
    };
    let district = new AMap.DistrictSearch(opts);
    //行政区查询
    // }
    district.search(name, (status, result) => {
      // if (_this.border_area != null) {
      //   _this.map.remove(_this.border_area); //清除上次结果
      //   _this.border_area = null;
      // }
      if (borderList.length > 0) {
        borderList.forEach((item) => {
          _this.aMap.remove(item); //清除上次结果
        });
        borderList = [];
      }
      // 外多边形坐标数组和内多边形坐标数组
      var outer = [
        new AMap.LngLat(-360, 90, true),
        new AMap.LngLat(-360, -90, true),
        new AMap.LngLat(360, -90, true),
        new AMap.LngLat(360, 90, true),
      ];

      var bounds = result.districtList[0].boundaries;

      // 如果 账号所属区域 为 市一级 则绘制 区边界
      // if (result.districtList[0].level == "city") {
      //   let districtList = result.districtList[0].districtList;
      //   districtList.forEach((item) => {
      //     district.search(item.adcode, (sta, res) => {
      //       let districtBounds = res.districtList[0].boundaries;
      //       if (districtBounds) {
      //         for (var i = 0; i < districtBounds.length; i += 1) {
      //           //构造MultiPolygon的path
      //           districtBounds[i] = [districtBounds[i]];
      //         }
      //         let border = new AMap.Polygon({
      //           path: districtBounds,
      //           zIndex: 1,
      //           // fillColor: "#71B3ff",
      //           fillColor: "",
      //           strokeWeight: 1.5,
      //           // strokeColor: "rgb(18, 201, 147)",
      //           strokeColor: "rgb(155, 155, 155)",
      //           bubble: true,
      //         });
      //         try {
      //           _this.aMap.add(border);
      //           borderList.push(border);
      //         } catch (error) {}
      //       }
      //     });
      //   });
      // }

      var pathArray = [outer];
      pathArray.push.apply(pathArray, bounds);
      if (bounds) {
        //生成行政区划polygon
        for (var i = 0; i < bounds.length; i += 1) {
          //构造MultiPolygon的path
          bounds[i] = [bounds[i]];
        }
        maskObj = new AMap.Polygon({
          path: pathArray,
          zIndex: 1,
          fillColor: "",
          strokeWeight: 3,
          strokeColor: "rgb(18, 201, 147)",
          bubble: true,
        });

        // let border_area = new AMap.Polygon({
        //   path: bounds,
        //   fillColor: "",
        //   // fillOpacity: 1,
        //   strokeWeight: 3,
        //   strokeColor: "rgb(18, 201, 147)",
        //   bubble: true,
        // });
        try {
          _this.aMap.add(maskObj);
          borderList.push(maskObj);
          if (_this.mapZoom != null) {
            // _this.aMap.setZoomAndCenter(_this.mapZoom, _this.mapCenter, true, 1000);
          } else {
            // _this.aMap.setFitView(border_area, true, [180, 150, 150, 150]); //视口自适应
            // _this.aMap.setFitView(border_area, true); //视口自适应
          }
        } catch (error) { }
      }
    });
  }

  /**
   * @description: 画热力图
   */
  drawheatmap() {
    if (!this.isSupportCanvas()) {
      alert(
        "热力图仅对支持canvas的浏览器适用,您所使用的浏览器不能使用热力图功能,请换个浏览器试试~"
      );
    }

    //详细的参数,可以查看heatmap.js的文档 http://www.patrick-wied.at/static/heatmapjs/docs.html
    //参数说明如下:
    /* visible 热力图是否显示,默认为true
   * opacity 热力图的透明度,分别对应heatmap.js的minOpacity和maxOpacity
   * radius 势力图的每个点的半径大小
   * gradient  {JSON} 热力图的渐变区间 . gradient如下所示
   *	{
   .2:'rgb(0, 255, 255)',
   .5:'rgb(0, 110, 255)',
   .8:'rgb(100, 0, 255)'
   }
   //初始值
   gradient: {
          0.5: 'blue',
          0.65: 'rgb(117,211,248)',
          0.7: 'rgb(0, 255, 0)',
          0.9: '#ffea00',
          1.0: 'red',
        },
   其中 key 表示插值的位置, 0-1
   value 为颜色值
   */
    this.aMap.plugin(["AMap.HeatMap"], () => {
      //初始化heatmap对象
      heatmap = new AMap.HeatMap(this.aMap, {
        radius: 50, //给定半径
        opacity: [0, 1],
        blur: 1,
        gradient: {
          0.1: "blue",
          0.4: "rgb(117,211,248)",
          0.6: "rgb(0, 255, 0)",
          0.8: "#ffea00",
          1.0: "red",
        },
      });
      heatmap.setDataSet({
        data: heatmapData["hangzhou"].heatmapData,
        max: 20,
      });
    });
  }

  //判断浏览区是否支持canvas
  isSupportCanvas() {
    let elem = document.createElement("canvas");
    return !!(elem.getContext && elem.getContext("2d"));
  }
  /**
   * @description: 清除热力图
   */
  removeheatmap() {
    if (heatmap) {
      heatmap.setMap(null);
    }
  }
  /**
   * @description: 绘制热门坠机点效果
   */
  drawPopularPoints() {
    let pointdata = [
      {
        latitude: 30.254939,
        longitude: 120.162374,
        icon: import.meta.env.VITE_BASE_PUBLICPATH + "/img/cockpit/bluepoint.png",
      },
      {
        latitude: 30.256528,
        longitude: 120.160323,
        icon: import.meta.env.VITE_BASE_PUBLICPATH + "/img/cockpit/bluepoint.png",
      },
      {
        latitude: 30.257161,
        longitude: 120.162661,
        icon: import.meta.env.VITE_BASE_PUBLICPATH + "/img/cockpit/bluepoint.png",
      },
      {
        latitude: 30.253106,
        longitude: 120.162384,
        icon: import.meta.env.VITE_BASE_PUBLICPATH + "/img/cockpit/bluepoint.png",
      },
      {
        latitude: 30.254122,
        longitude: 120.163689,
        icon: import.meta.env.VITE_BASE_PUBLICPATH + "/img/cockpit/bluepoint.png",
      },

      {
        latitude: 30.255906,
        longitude: 120.165234,
        icon: import.meta.env.VITE_BASE_PUBLICPATH + "/img/cockpit/bluepoint.png",
      },
      {
        latitude: 30.251835,
        longitude: 120.164134,
        icon: import.meta.env.VITE_BASE_PUBLICPATH + "/img/cockpit/redpoint.png",
      },
      {
        latitude: 30.237139,
        longitude: 120.211087,
        icon: import.meta.env.VITE_BASE_PUBLICPATH + "/img/cockpit/redpoint.png",
      },
      {
        latitude: 30.236143,
        longitude: 120.207782,
        icon: import.meta.env.VITE_BASE_PUBLICPATH + "/img/cockpit/redpoint.png",
      },
      {
        latitude: 30.233148,
        longitude: 120.207005,
        icon: import.meta.env.VITE_BASE_PUBLICPATH + "/img/cockpit/redpoint.png",
      },
      {
        latitude: 30.22831,
        longitude: 120.222312,
        icon: import.meta.env.VITE_BASE_PUBLICPATH + "/img/cockpit/redpoint.png",
      },
      {
        latitude: 30.224907,
        longitude: 120.222904,
        icon: import.meta.env.VITE_BASE_PUBLICPATH + "/img/cockpit/redpoint.png",
      },
      {
        latitude: 30.230692,
        longitude: 120.225489,
        icon: import.meta.env.VITE_BASE_PUBLICPATH + "/img/cockpit/redpoint.png",
      },
    ];
    this.drawMassPoint(pointdata, "PopularPoints", false, [20, 20], false);
    let reddata = [
      {
        longitude: 120.158505,
        latitude: 30.257189,
      },
      {
        longitude: 120.162892,
        latitude: 30.254157,
      },
      {
        longitude: 120.213696,
        latitude: 30.240756,
      }, {
        longitude: 120.229108,
        latitude: 30.235861,
      },
    ];
    reddata.forEach((item, index) => {
      var marker = new AMap.Marker({
        position: [item.longitude, item.latitude],
        content: '<div class="custom-content-marker"></div>',
        offset: new AMap.Pixel(-35, -35),
        // title: `${item.name}`,
      });
      this.removeMarkers.push(marker);
      this.aMap.add(marker);
    });
  }

  /**
   * @description: 添加热气球 Marker
   */
  drawBalloonMarker(data, icon) {
    let marker = new AMap.Marker({
      position: data,
      content: `<div style="position:relative;width:100px;height:125px;background:url('/img/cockpit/${icon}');background-size:100% 100%;"></div>`,
      offset: new AMap.Pixel(-35, -35),
    });
    this.removeMarkers.push(marker);
    this.aMap.add(marker);
  }

  /**
   * @description: 添加多发预警预警图标
   */
  drawDuofaMarker(position, icon, data) {
    let size = data.alarmLevel === "firstLevel" ? 1.2 : data.alarmLevel === "secondLevel" ? 1 : 0.8
    let width = 75 * size;
    let height = 56 * size;
    let marker = new AMap.Marker({
      position: position,
      content: `<div style="position:relative;width:${width}px;height:${height}px;background:url('/img/cockpit/${icon}');background-size:100% 100%;"></div>`,
      offset: new AMap.Pixel(-35, -25),
      zIndex: 1300,
    });
    marker.setLabel({
      direction: 'top',
      offset: new AMap.Pixel(0, 0),  //设置文本标注偏移量
      content: `<div style="height:24px;line-height:24px;color:#fff;font-size:16px;background:rgba(55,55,55,0.6);">${data.name}</div>`, //设置文本标注内容
    });
    marker.on("click", (e) => {
      // this.flyToTarget(position)
      OpnePop(data.alarmType, data.alarmLevel);
    });
    this.removeMarkers.push(marker);
    this.aMap.add(marker);
  }

  /**
   * @description: 添加气象设备图标
   */
  drawwindicon() {
    let windicon = new AMap.Marker({
      map: this.aMap,
      position: new AMap.LngLat(120.191093, 30.206219),
      icon: new AMap.Icon({
        size: new AMap.Size(40, 40), // 图标尺寸
        image: import.meta.env.VITE_BASE_PUBLICPATH + `/img/cockpit/Frame4.png`,
        imageSize: new AMap.Size(35, 40),
      }),
      offset: new AMap.Pixel(-20, -20),
      // extData: item,
    });
    this.aMap.add(windicon);
    return windicon;
  }
  /**
   * @description: 绘制定向反制效果 用于演示
   */
  drawdirectional() {
    let directionalMarker = new AMap.Marker({
      map: this.aMap,
      position: new AMap.LngLat(120.101225, 30.262237),
      icon: new AMap.Icon({
        size: new AMap.Size(29, 35), // 图标尺寸
        image: import.meta.env.VITE_BASE_PUBLICPATH + `/img/cockpit/Frame1.png`,
        imageSize: new AMap.Size(29, 35),
      }),
      offset: new AMap.Pixel(-15, -15),
      // extData: item,
    });
    this.aMap.add(directionalMarker);
    return directionalMarker;
  }

  /**
   * @description:  测距
   */
  drawRanging = (val) => {
    if (val) {
      if (mouseTool == null) {
        // 测距、测面积使用
        mouseTool = new AMap.MouseTool(this.aMap);
      }
      mouseTool.rule({
        startMarkerOptions: {
          //可缺省
          icon: new AMap.Icon({
            size: new AMap.Size(19, 31), //图标大小
            imageSize: new AMap.Size(19, 31),
            image: import.meta.env.VITE_BASE_PUBLICPATH + "/img/cockpit/start.png",
          }),
          offset: new AMap.Pixel(-9, -31),
          zIndex: 2000,
          bubble: true,
        },
        endMarkerOptions: {
          //可缺省
          icon: new AMap.Icon({
            size: new AMap.Size(19, 31), //图标大小
            imageSize: new AMap.Size(19, 31),
            image: import.meta.env.VITE_BASE_PUBLICPATH + "/img/cockpit/end.png",
          }),
          offset: new AMap.Pixel(-9, -31),
          zIndex: 2000,
        },
        midMarkerOptions: {
          //可缺省
          icon: new AMap.Icon({
            size: new AMap.Size(19, 31), //图标大小
            imageSize: new AMap.Size(19, 31),
            image: import.meta.env.VITE_BASE_PUBLICPATH + "/img/cockpit/mid.png",
          }),
          offset: new AMap.Pixel(-9, -31),
          zIndex: 2000,
        },
        lineOptions: {
          //可缺省
          strokeStyle: "solid",
          strokeColor: "#FF33FF",
          strokeOpacity: 1,
          strokeWeight: 4,
          zIndex: 2000,
        },
      });
    } else {
      if (mouseTool != null) {
        mouseTool.close(true);
      }
    }
  };
  /**
   * @description: 默认视角
   */
  defaultAngle = (defaultViewShow) => {
    defaultViewShowFun = defaultViewShow;
    this.aMap.setRotation(5);
    this.aMap.setPitch(45);
    this.aMap.setZoomAndCenter(12.2, [120.180924, 30.186115]);
  };

  /**
   * @description: 绘制海量点
   * @param {*} data 点坐标数据
   * @param {*} type 海量点类别
   * @param {*} flag 判断初始化
   * @param {*} size 图标的大小
   * @param {*} collisionflag 图标是否避让
   */
  drawMassPoint = (
    data,
    type,
    flag = false,
    size = [29, 35],
    collisionflag = true
  ) => {
    // 创建海量点 图层
    const layer = new AMap.LabelsLayer({
      zooms: [3, 20],
      // 该层内标注是否避让
      collision: collisionflag,
      zIndex: 1200,
      opacity: 1,
      // 设置 allowCollision：true，可以让标注避让用户的标注
      allowCollision: collisionflag,
    });
    // 图标
    let labelsData = [];
    // 海量点 数据处理
    data.forEach((item) => {
      let labelMarker = new AMap.LabelMarker({
        name: item.id,
        position: [Number(item.longitude), Number(item.latitude)],
        icon: {
          // 图标类型，现阶段只支持 image 类型
          type: "image",
          // 图片 url
          image: item.icon,
          // 图片尺寸
          size: size,
          offset: new AMap.Pixel(0, 15),
          // 图片相对 position 的锚点，默认为 bottom-center
          anchor: "bottom-center",
        },
        gridSize: 50,
        title: item.name,
        extData: item,
        zIndex: 1200,
        bubble: true,
      });
      if (!flag) {
        labelMarker.on("click", (e) => {
          let state = false;
          this.aMap.setZoomAndCenter(
            17,
            [Number(item.longitude), Number(item.latitude)],
            state,
            1000
          );
          OpnePop(item.id, item.EntityType);
          return false;
        });
      }
      labelsData.push(labelMarker);
    });
    // 海量点图层 加入数据
    layer.add(labelsData);
    // 海量点 图层 加入地图
    this.aMap.add(layer);

    switch (type) {
      case "company":
        this.companyLayer = layer;
        break;
      case "mhAirport":
        this.mhAirportLayer = layer;
        break;
      case "thAirport":
        this.thAirportLayer = layer;
        break;
      case "czAirport":
        this.czAirportLayer = layer;
        break;
      case "UAVAirport":
        this.UAVAirportLayer = layer;
        break;
      case "zhence":
        this.zhenceLayer = layer;
        break;
      case "fanzhi":
        this.fanzhiLayer = layer;
        break;
      case "wxd":
        this.wxdLayer = layer;
        break;
      case "qixiang":
        this.weatherDeviceLayer = layer;
        break;
      case "youpian":
        this.youpianLayer = layer;
        break;
      case "PopularPoints":
        this.PopularPointslayer = layer;
    }
  };


  /**
   * @description: 移除海量点
   * @param {*} type 海量点类别
   */
  removeMassPoint = (type) => {
    switch (type) {
      case "company":
        if (!this.companyLayer) { return; }
        this.aMap.remove(this.companyLayer);
        this.companyLayer = null;
        break;
      case "mhAirport":
        if (!this.mhAirportLayer) { return; }
        this.aMap.remove(this.mhAirportLayer);
        this.mhAirportLayer = null;
        break;
      case "thAirport":
        if (!this.thAirportLayer) { return; }
        this.aMap.remove(this.thAirportLayer);
        this.thAirportLayer = null;
        break;
      case "czAirport":
        if (!this.czAirportLayer) { return; }
        this.aMap.remove(this.czAirportLayer);
        this.czAirportLayer = null;
        break;
      case "UAVAirport":
        if (!this.UAVAirportLayer) { return; }
        this.aMap.remove(this.UAVAirportLayer);
        this.UAVAirportLayer = null;
        break;
      case "zhence":
        if (!this.zhenceLayer) { return; }
        this.aMap.remove(this.zhenceLayer);
        this.zhenceLayer = null;
        break;
      case "fanzhi":
        if (!this.fanzhiLayer) { return; }
        this.aMap.remove(this.fanzhiLayer);
        this.fanzhiLayer = null;
        break;
      case "wxd":
        if (!this.wxdLayer) { return; }
        this.aMap.remove(this.wxdLayer);
        this.wxdLayer = null;
        break;
      case "qixiang":
        if (!this.weatherDeviceLayer) { return; }
        this.aMap.remove(this.weatherDeviceLayer);
        this.weatherDeviceLayer = null;
        break;
      case "youpian":
        if (!this.youpianLayer) { return; }
        this.aMap.remove(this.youpianLayer);
        this.youpianLayer = null;
        break;
      case "PopularPoints":
        if (!this.PopularPointslayer) { return; }
        if (this.PopularPointslayer) {
          this.aMap.remove(this.PopularPointslayer);
          this.PopularPointslayer = null;
        }
        if (this.removeMarkers.length > 0) {
          this.removeMarkers.forEach((item) => {
            this.aMap.remove(item);
          });
        }
        break;
      case "reqiqiu":
        if (this.removeMarkers.length > 0) {
          this.removeMarkers.forEach((item) => {
            this.aMap.remove(item);
          });
        }
        break;
      case "duofa":
        if (this.removeMarkers.length > 0) {
          this.removeMarkers.forEach((item) => {
            this.aMap.remove(item);
          });
        }
        break;
    }
  };


  /**
   * @description: 显示温度
   * @param {*} data 天气数据
   */
  drawTemp = (data) => {
    this.aMap.setRotation(5);
    this.aMap.setPitch(0);
    this.aMap.setZoomAndCenter(10.3, [120.168392, 30.159335]);
    let markerList = [];
    data.forEach((item) => {
      let marker = new AMap.Marker({
        name: item.id,
        position: [Number(item.lon), Number(item.lat)],
        icon: item.icon,
        offset: new AMap.Pixel(0, 0),
        zIndex: 120,
      });
      marker.setLabel({
        direction: "right",
        offset: new AMap.Pixel(10, 0), //设置文本标注偏移量
        content: `<div class="markerLabel">${item.label} ${item.condition} ${item.temp}℃</div>`, //设置文本标注内容
      });
      markerList.push(marker);
    });
    this.aMap.add(markerList);
    return markerList;
  };


  /**
   * @description: 禁飞区图表
   */
  drawIconTemp = (data, flag = false) => {
    let markerList = [];
    data.forEach((item) => {
      let marker = new AMap.Marker({
        name: item.id,
        position: [Number(item.longitude), Number(item.latitude) + 0.03],
        icon: new AMap.Icon({
          size: new AMap.Size(35, 35), // 图标尺寸
          image: item.icon,
          imageSize: new AMap.Size(35, 35),
        }),
        offset: new AMap.Pixel(-17, -17),
        zIndex: 10,
      });
      if (flag) {
        marker.setLabel({
          direction: "right",
          offset: new AMap.Pixel(-10, -40), //设置文本标注偏移量
          content: "", //设置文本标注内容
        });
        // <div class="markerLabel">${"发现无人机降落，已自动通知无人机避让"}</div>
        ElMessage.warning({
          message:
            "发现民航飞机（CA5527）当前位置附近存在无人机驾驶航空器，已通知相关人员及时避让。",
          duration: 10000,
        });
      }
      markerList.push(marker);
    });
    this.aMap.add(markerList);
    return markerList;
  };

  /**
   * @description: 显示风力
   * @param {*} data 天气数据
   */
  drawWind = (data) => {
    this.aMap.setRotation(5);
    this.aMap.setPitch(0);
    this.aMap.setZoomAndCenter(10.3, [120.168392, 30.159335]);
    let markerList = [];
    data.forEach((item) => {
      let marker = new AMap.Marker({
        name: item.id,
        position: [Number(item.lon), Number(item.lat)],
        icon: import.meta.env.VITE_BASE_PUBLICPATH + "/img/weather/windLevel.png",
        offset: new AMap.Pixel(0, 0),
        zIndex: 120,
      });
      marker.setLabel({
        direction: "right",
        offset: new AMap.Pixel(10, 0), //设置文本标注偏移量
        content: `<div class="markerLabel">${item.label}  ${item.windSpeed}km/h  ${item.windDir} ${item.windLevel}级</div>`, //设置文本标注内容
      });
      markerList.push(marker);
    });
    this.aMap.add(markerList);
    return markerList;
  };

  /**
   * @description: 显示降雨
   * @param {*} data 天气数据
   */
  drawRain = (data) => {
    this.aMap.setRotation(5);
    this.aMap.setPitch(0);
    this.aMap.setZoomAndCenter(10.3, [120.168392, 30.159335]);
    let markerList = [];
    data.forEach((item) => {
      let marker = new AMap.Marker({
        name: item.id,
        position: [Number(item.lon), Number(item.lat)],
        icon: item.icon,
        offset: new AMap.Pixel(0, 0),
        zIndex: 120,
      });
      marker.setLabel({
        direction: "right",
        offset: new AMap.Pixel(10, 0), //设置文本标注偏移量
        content: `<div class="markerLabel">${item.label}  ${item.condition}</div>`, //设置文本标注内容
      });
      markerList.push(marker);
    });
    this.aMap.add(markerList);
    return markerList;
  };

  /**
   * @description: 气象设备
   * @param {*} data 天气数据
   */
  deviceMeteorological = (data, type) => {
    let list = data;
    let list2 = [];
    let idList = [];
    for (var i = 0; i < list.length; i++) {
      let str = null;
      let windDirection = "";
      if (list[i].windDirection === "EAST") windDirection = "东风";
      else if (list[i].windDirection === "WEST") windDirection = "西风";
      else if (list[i].windDirection === "SOUTH") windDirection = "南风";
      else if (list[i].windDirection === "NORTH") windDirection = "北风";
      else if (list[i].windDirection === "SOUTHWEST") windDirection = "西南风";
      else if (list[i].windDirection === "SOUTHEAST") windDirection = "东南风";
      else if (list[i].windDirection === "NORTHWEST") windDirection = "西北风";
      else if (list[i].windDirection === "NORTHEAST") windDirection = "东北风";
      let icon;
      if (type == "WD") {
        str = list[i].airTemp + "℃";
        icon = new AMap.Icon({
          // 图标尺寸
          size: new AMap.Size(32, 32),
          // 图标的取图地址
          image: import.meta.env.VITE_BASE_PUBLICPATH + "/img/weather/temp.png",
          // 图标所用图片大小
          imageSize: new AMap.Size(32, 32),
        });
      } else if (type == "FL") {
        idList.push(list[i].id);
        str =
          list[i].windSpeed +
          "km/h" +
          " " +
          windDirection +
          " " +
          list[i].windForce +
          "级";
        icon = new AMap.Icon({
          // 图标尺寸
          size: new AMap.Size(32, 32),
          // 图标的取图地址
          image: import.meta.env.VITE_BASE_PUBLICPATH + "/img/weather/windy.png",
          // 图标所用图片大小
          imageSize: new AMap.Size(32, 32),
        });
      } else if (type == "JS") {
        str = list[i].currentRainfall + "mm";
        icon = new AMap.Icon({
          // 图标尺寸
          size: new AMap.Size(32, 32),
          // 图标的取图地址
          image: import.meta.env.VITE_BASE_PUBLICPATH + "/img/weather/rain.png",
          // 图标所用图片大小
          imageSize: new AMap.Size(32, 32),
        });
      }

      let marker = new AMap.Marker({
        position: [parseFloat(list[i].gpsLng), parseFloat(list[i].gpsLat)],
        icon: icon,
        offset: new AMap.Pixel(30, 0),
        zIndex: 120,
        id: list[i].id
      });
      marker.setLabel({
        direction: "right",
        offset: new AMap.Pixel(10, 0), //设置文本标注偏移量
        content: `<div class="markerLabel">${str}</div>`, //设置文本标注内容
      });
      list2.push(marker);
    }
    this.aMap.add(list2);
    if (idList.length > 0) {
      for (var i = 0; i < idList.length; i++) {
        list2.forEach(item => {
          if (idList[i] == item._opts.id) {
            setTimeout(() => {
              this.aMap.remove(item)
            }, 30000)
          }
        })
      }
    }
    return list2;
  };

  /**
   * @description: 处理设备信息 定向设备 全向设备 GPS 设备
   * @param {*} arr
   */
  equipmentType_draw(arr) {
    arr = [
      {
        deviceId: 631,
        id: 6981,
        name: "黄龙体育中心-定向反制",
        status: 1,
        typeId: 5,
        creTime: "2024-01-29 14:20:23",
        longitude: "120.101225",
        latitude: "30.262237",
        isUnmanned: 0,
        type: 2,
        strikeSeconds: 60,
        strikeRadius: null,
        trackCalibrationAngle: null,
        calibrationChangeAngle: null,
        trackDisable: null,
        colourCss: "#c1bd68",
        includedAngle: null,
        sectorRadius: null,
        installHeight: 80,
        unattendedState: false,
        countdown: false,
      },
    ];
    orientationInfoList = [];
    arr.forEach((item) => {
      if (item.typeId == 5) {
        orientationInfoList.push({
          id: item.deviceId,
          longitude: item.longitude,
          latitude: item.latitude,
          strikeRadius: item.strikeRadius == null ? 1500 : item.strikeRadius,
          includedAngle: item.includedAngle == null ? 120 : item.includedAngle,
        });
      }
    });
    setTimeout(() => {
      this.drawOrientantionSector();
      this.drawDeviceAnimation(arr[0]);
    }, 2000);
  }
  /**
   * @description: 绘制定向设备扇形
   */
  drawOrientantionSector() {
    if (orientationInfoList.length > 0) {
      orientationInfoList.map((j) => {
        this.drawRadarCircle(
          [Number(j.longitude), Number(j.latitude)],
          Number(j.strikeRadius),
          "rgba(255, 238, 111,1)",
          orientationCircleList,
          "dashed"
        );
      });
    }
    let arr = [];
    let list = [];
    if (orientationInfoList.length > 0) {
      list = orientationInfoList;

      list.map((item) => {
        arr.push({
          deviceId: item.id,
        });
      });
    }
    if (arr.length > 0) {
      // let res = await droneDeviceAngle({ deviceIds: arr });
      let res = {
        code: "200",
        data: [
          {
            deviceId: 631,
            // horizontal_angle: "153.84",
            // vertical_angle: "358.24",
            horizontal_angle: "270",
            vertical_angle: "358.24",
          },
        ],
        msg: "操作成功",
      };
      if (res.code == 200 && res.data.length > 0) {
        res.data.map((x) => {
          list.map((j) => {
            if (j.id == x.deviceId) {
              j.horizontalAngle = x.horizontal_angle;
              j.verticalAngle = x.vertical_angle;
            }
          });
        });
        nextTick(() => {
          list.map((k) => {
            //绘制扇形
            this.drawDeviceCircles(
              Number(k.longitude),
              Number(k.latitude),
              Number(k.horizontalAngle - 60),
              120,
              Number(k.strikeRadius),
              orientationSector,
              "rgba(255, 238, 111,0.1)",
              k
            );
          });
        });
      }
    }
  }

  /**
   * @description: 绘制雷达圆
   * @param {*} arr 雷达圆 位置
   * @param {*} radius 半径
   * @param {*} color 颜色
   * @param {*} example 存放数组实例  solid
   */
  drawRadarCircle(
    arr,
    radius,
    color,
    example,
    strokeStyle,
    fillOpacity = 0,
    fillColor = "rgba(0, 0, 0,0)"
  ) {
    const tt = new AMap.Circle({
      center: [arr[0], arr[1]],
      radius: radius,
      strokeColor: color, //线颜色
      fillOpacity: fillOpacity, //填充透明度
      fillColor: fillColor,
      strokeOpacity: 1,
      strokeStyle: strokeStyle, //轮廓线样式
      strokeWeight: 3,
      zIndex: 999,
    });
    aMap.add(tt);
    example.push(tt);
  }

  /**
   * @description: 绘制扇形
   * @param {*} longitude 扇形原点纬度
   * @param {*} latitude 扇形原点经度
   * @param {*} angle 旋转角度 相对于正北
   * @param {*} sectorAngle 扇形夹角
   * @param {*} radius 扇形边长
   * @param {*} example 绘制图形存放数组
   * @param {*} color 绘制图形的颜色
   * @param {*} special 特殊情况 默认为null 正常存数组 不为难 根据key 存对象
   */
  drawDeviceCircles(
    longitude,
    latitude,
    angle,
    sectorAngle = 120,
    radius = 1495,
    example,
    color = "#60a0bf",
    special = null
  ) {
    let arr = [];
    for (let i = 0; i < sectorAngle; i = i + 5) {
      let b = this.calculatingTargetPoints(
        longitude,
        latitude,
        angle + sectorAngle - i,
        radius
      );

      let a = this.calculatingTargetPoints(
        longitude,
        latitude,
        angle + sectorAngle - (i + 5),
        radius
      );
      arr.push([b.lng, b.lat]);
      arr.push([a.lng, a.lat]);
    }
    let multiPoint = turf.multiPoint(arr);
    let list = turf.cleanCoords(multiPoint).geometry.coordinates;
    list.unshift([longitude, latitude]);
    const tt = new AMap.Polygon({
      zIndex: 3000,
      path: list,
      fillColor: color,
      strokeColor: color,
      strokeOpacity: 0,
      strokeWeight: 1,
      fillOpacity: 0.2,
    });
    if (aMap) {
      aMap.add(tt);
    }
    if (special == null) {
      example.push(tt);
    } else {
      example[special.id] = tt;
    }
  }

  /**
   * @description: 根据角度 距离 计算点位置
   * @param {*} lng 已知点纬度
   * @param {*} lat 已知点经度
   * @param {*} brng 角度
   * @param {*} dist 距离
   * @return {*} 经纬度
   */
  calculatingTargetPoints(lng, lat, brng, dist) {
    function rad(d) {
      return (d * Math.PI) / 180.0;
    }

    function deg(x) {
      return (x * 180) / Math.PI;
    }
    // eslint-disable
    //大地坐标系资料WGS-84 长半径a=6378137 短半径b=6356752.3142 扁率f=1/298.2572236
    let a = 6378137;
    let b = 6356752.3142;
    let f = 1 / 298.257223563;

    let lon1 = lng * 1;
    let lat1 = lat * 1;
    let s = dist;
    let alpha1 = rad(brng);
    let sinAlpha1 = Math.sin(alpha1);
    let cosAlpha1 = Math.cos(alpha1);

    let tanU1 = (1 - f) * Math.tan(rad(lat1));
    let cosU1 = 1 / Math.sqrt(1 + tanU1 * tanU1),
      sinU1 = tanU1 * cosU1;
    let sigma1 = Math.atan2(tanU1, cosAlpha1);
    let sinAlpha = cosU1 * sinAlpha1;
    let cosSqAlpha = 1 - sinAlpha * sinAlpha;
    let uSq = (cosSqAlpha * (a * a - b * b)) / (b * b);
    let A = 1 + (uSq / 16384) * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq)));
    let B = (uSq / 1024) * (256 + uSq * (-128 + uSq * (74 - 47 * uSq)));

    let sigma = s / (b * A),
      sigmaP = 2 * Math.PI;
    while (Math.abs(sigma - sigmaP) > 1e-12) {
      var cos2SigmaM = Math.cos(2 * sigma1 + sigma);
      var sinSigma = Math.sin(sigma);
      var cosSigma = Math.cos(sigma);
      let deltaSigma =
        B *
        sinSigma *
        (cos2SigmaM +
          (B / 4) *
          (cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM) -
            (B / 6) *
            cos2SigmaM *
            (-3 + 4 * sinSigma * sinSigma) *
            (-3 + 4 * cos2SigmaM * cos2SigmaM)));
      sigmaP = sigma;
      sigma = s / (b * A) + deltaSigma;
    }

    let tmp = sinU1 * sinSigma - cosU1 * cosSigma * cosAlpha1;
    let lat2 = Math.atan2(
      sinU1 * cosSigma + cosU1 * sinSigma * cosAlpha1,
      (1 - f) * Math.sqrt(sinAlpha * sinAlpha + tmp * tmp)
    );
    let lambda = Math.atan2(
      sinSigma * sinAlpha1,
      cosU1 * cosSigma - sinU1 * sinSigma * cosAlpha1
    );
    let C = (f / 16) * cosSqAlpha * (4 + f * (4 - 3 * cosSqAlpha));
    let L =
      lambda -
      (1 - C) *
      f *
      sinAlpha *
      (sigma +
        C *
        sinSigma *
        (cos2SigmaM + C * cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM)));

    let revAz = Math.atan2(sinAlpha, -tmp); // final bearing

    let lngLatObj = { lng: lon1 + deg(L), lat: deg(lat2) };
    return lngLatObj;
    //eslint-enable
  }

  /**
   * @description: 设备下发命令时 开启动画
   * @param {*} item 设备信息
   * @param {*} false 是否关闭动画
   */
  drawDeviceAnimation(item, flag = false) {
    if (item.typeId == 5) {
      //定向设备
      // 删除定向设备对应扇形
      if (orientationSector[item.deviceId]) {
        aMap.remove(orientationSector[item.deviceId]);
        orientationSector[item.deviceId] = null;
        delete orientationSector[item.deviceId];
      }
      let equipmentInfo = deviceOptions.find(
        (option) => option.deviceId === item.deviceId
      );
      let radius = 10;
      let sop = 0; // 图形的边框颜色透明度
      // let sw = 8; // 图形的边框大小
      let sw = 3; // 图形的边框大小
      let fillop = 0.5; // 图形的填充颜色
      let i = 0;
      let sectorAngle = equipmentInfo.includedAngle
        ? equipmentInfo.includedAngle
        : 120;
      if (sectortimer[item.deviceId] != null) {
        clearInterval(sectortimer[item.deviceId]);
        sectortimer[item.deviceId] = null;
      }

      let timer = setInterval(() => {
        let horizontalAngle = 0;
        orientationInfoList.forEach((i) => {
          if (i.id === item.deviceId) {
            horizontalAngle = i.horizontalAngle;
          }
        });
        let angle = horizontalAngle - sectorAngle / 2;
        this.drawFanBorder(
          Number(equipmentInfo.longitude),
          Number(equipmentInfo.latitude),
          angle,
          Number(sectorAngle),
          radius,
          sectorarr,
          equipmentInfo.colourCss,
          fillop,
          sw,
          sop
        );
        radius += 180;
        fillop -= 0.05;
        i = i + 1;
        if (i == 10) {
          radius = 10;
          i = 0;
          fillop = 0.5;
          sectorarr.map((item) => {
            aMap.remove(item);
          });
        }
      }, 150);
      sectortimer[item.deviceId] = timer;
      if (!flag) {
        if (closeSectortimer[item.deviceId] != null) {
          clearTimeout(closeSectortimer[item.deviceId]);
          closeSectortimer[item.deviceId] = null;
        }
        let timeOut = setTimeout(() => {
          clearInterval(sectortimer[item.deviceId]);
          sectortimer[item.deviceId] = null;
          sectorarr.map((item) => {
            aMap.remove(item);
          });
          if (closeSectortimer[item.deviceId] != null) {
            clearTimeout(closeSectortimer[item.deviceId]);
            closeSectortimer[item.deviceId] = null;
          }
        }, 1000 * 60);
        closeSectortimer[item.deviceId] = timeOut;
      }

      deviceCount[item.deviceId].count = 60;
      deviceCount[item.deviceId].countdown = false; //倒计时
      deviceCount[item.deviceId].counterType = item.counterType
        ? item.counterType
        : ""; // 反制类型

      // 清除对应 旧 定时器
      if (deviceCount[item.deviceId].timer != null) {
        clearInterval(deviceCount[item.deviceId].timer);
        deviceCount[item.deviceId].timer = null;
        delete deviceCount[item.deviceId].timer;
      }
      // 开启对应 新 定时器
      deviceCount[item.deviceId].timer = setInterval(() => {
        // 倒计时
        deviceCount[item.deviceId].count--; //递减
        localStorage.setItem("deviceCount", JSON.stringify(deviceCount));

        // 倒计时归零
        if (deviceCount[item.deviceId].count <= 0) {
          // <=0 变成获取按钮
          deviceCount[item.deviceId].countdown = true;
          deviceCount[item.deviceId].counterType = "";
          // 清除对应定时器
          if (deviceCount[item.deviceId].timer != null) {
            clearInterval(deviceCount[item.deviceId].timer);
            deviceCount[item.deviceId].timer = null;
            delete deviceCount[item.deviceId].timer;
          }
          localStorage.setItem("deviceCount", JSON.stringify(deviceCount));
          orientationInfoList.map((j) => {
            if (j.id == item.deviceId) {
              j.horizontalAngle = "";
            }
          });
        }
      }, 1000); //1000毫秒后执行
    }
  }

  /**
   * @description: 绘制扇形边框 = truf新方法绘制扇形
   * @param {*} longitude 扇形原点纬度
   * @param {*} latitude 扇形原点经度
   * @param {*} angle 旋转角度 相对于正北
   * @param {*} sectorAngle 扇形夹角
   * @param {*} radius 扇形边长
   * @param {*} example 绘制图形存放数组
   * @param {*} color 绘制图形的颜色
   * @param {*} fillop 图形的填充颜色
   * @param {*} sw 图形的边框大小
   * @param {*} sop 图形的边框颜色透明度
   */
  drawFanBorder(
    longitude,
    latitude,
    angle,
    sectorAngle = 240,
    radius = 1495,
    example,
    color = "#c1bd68",
    fillop,
    sw,
    sop
  ) {
    let arr = [];
    for (let i = 0; i < sectorAngle; i = i + 5) {
      let b = this.calculatingTargetPoints(
        longitude,
        latitude,
        angle + sectorAngle - i,
        radius
      );

      let a = this.calculatingTargetPoints(
        longitude,
        latitude,
        angle + sectorAngle - (i + 5),
        radius
      );
      arr.push([b.lng, b.lat]);
      arr.push([a.lng, a.lat]);
    }
    let multiPoint = turf.multiPoint(arr);
    let list = turf.cleanCoords(multiPoint).geometry.coordinates;
    list.unshift([longitude, latitude]);
    const tt = new AMap.Polygon({
      zIndex: 3000,
      path: list,
      fillColor: color,
      strokeColor: color,
      fillOpacity: fillop,
      strokeWeight: sw,
      strokeOpacity: sop,
      bubble: true,
    });
    if (tt) {
      aMap.add(tt);
    }
    example.push(tt);
  }

  /**
   * @description: 清除 反制演示   反制设备动画 反制图标
   */
  clearEquipment() {
    if (orientationCircleList.length > 0) {
      orientationCircleList.forEach((item) => {
        aMap.remove(item);
      });
      orientationCircleList = [];
    }
    for (let key in sectortimer) {
      if (sectortimer[key]) {
        clearInterval(sectortimer[key]);
        sectortimer[key] = null;
        delete sectortimer[key];
      }
    }
    if (sectorarr.length > 0) {
      sectorarr.map((item) => {
        aMap.remove(item);
      });
      sectorarr = [];
    }
    for (let key in orientationSector) {
      aMap.remove(orientationSector[key]);
      delete orientationSector[key];
    }
  }

  /**
   * @description: 显示风力
   * @param {*} data 天气数据
   */
  removeWeather = (data) => {
    this.aMap.remove(data);
  };

  /**
 * @description: 添加带说明图标
 * @param {*} position 坐标
 */
  drawLabelMarker(position, icon, name, size = [25, 30]) {
    let marker = new AMap.Marker({
      position,
      content: `<div style="position:relative;width:${size[0]}px;height:${size[1]}px;background:url('/img/cockpit/${icon}');background-size:100% 100%;"></div>`,
      offset: new AMap.Pixel(-20, -45),
      zIndex: 1200,
    });
    if (name !== 'null') marker.setLabel({
      direction: 'top',
      offset: new AMap.Pixel(0, 0),  //设置文本标注偏移量
      content: `<div style="height:20px;line-height:20px;color:#fff;font-size:12px;background:rgba(55,55,55,0.6);">${name}</div>`, //设置文本标注内容
    });
    this.removeMarkers.push(marker);
    this.aMap.add(marker);
    // return marker;
  }

  drawLabelMarker2(position, icon, name, size = [25, 30]) {
    let marker = new AMap.Marker({
      position,
      content: `<div style="position:relative;width:${size[0]}px;height:${size[1]}px;background:url('/img/cockpit/${icon}');background-size:100% 100%;"></div>`,
      // offset: new AMap.Pixel(-20, -45),
      offset: new AMap.Pixel(-200, -200),
      zIndex: 1200,
    });
    if (name !== 'null') marker.setLabel({
      direction: 'top',
      offset: new AMap.Pixel(0, 0),  //设置文本标注偏移量
      content: `<div style="height:20px;line-height:20px;color:#fff;font-size:12px;background:rgba(55,55,55,0.6);">${name}</div>`, //设置文本标注内容
    });
    this.removeMarkers.push(marker);
    this.aMap.add(marker);
    // return marker;
  }

  /**
   * @description: 设置视角
   * @param {*} position 视角坐标
   */
  flyToTarget(position, zoom = 13, rotation = 5) {
    this.aMap.setZoomAndCenter(zoom, position);
    this.aMap.setRotation(rotation);
    this.aMap.setPitch(0);
  }
}
export default Controller;
